<?php
	/*
		Informing the location of the external program
	*/
	$pdf2swf = "/Users/name/RealisticBooks/installed/bin/pdf2swf";
	$swfstring = "/Users/name/RealisticBooks/installed/bin/swfstrings";
	$pdftotext = "/Users/name/RealisticBooks/installed/bin/pdftotext";
	$ghostscript = "/Users/name/RealisticBooks/installed/bin/gs";
	$tidy = "/Users/name/RealisticBooks/installed/bin/tidy";
	
	/*
		Informing the location of the uploading directory
	*/
	$uploaddir = "/Users/name/RealisticBooks/installed/htdocs/Bookmaker/bookdir";
	$fontdir = "/Users/name/RealisticBooks/installed/htdocs/Bookmaker/fontdir";
	$time_log = "/Users/name/RealisticBooks/installed/htdocs/Bookmaker/time.log";
	
	
	/*
		The proxy information
	*/	
	$username = "name";
	$password = "pwd";
	$proxyaddr = "tcp://proxy.scms.waikato.ac.nz:8080";

	/*
		Utility variables
	*/
	$wikiaddr = "http://wdm.cs.waikato.ac.nz:8080/service?";
	$maxchars = 150000;
	$book = "repository/orig_book.htm";
	$wikibook = "book.htm";
				
	/*
		Tidy the text input file into an XHTMLfile
		@param string $folder_name the path to the book directory
		@param string $input_file the path to the input XHTML file
	*/
	function tidyText ($folder_name, $input_file) {
		$fname = basename($input_file);
		$output_file = $folder_name."/tidy@".$fname; 
		
		$block_tags = "section, description, metadata, text, ".
					  "annotationlist, annotation, highlighted, soc, toc, ".
					  "newline, bob, textformat, bobitem, pagetext";
		$empty_tags = "newpage, line, bookmark, newlink, newimage";
		$tidy_options = escapeshellarg($GLOBALS['tidy']);
		$tidy_options .= " -wrap 0 -asxml --tidy-mark n --numeric-entities y";
		$tidy_options .= " --new-blocklevel-tags \"".$block_tags."\"";
		$tidy_options .= " --new-empty-tags \"".$empty_tags."\"";
		//$tidy_options .= " --new-inline-tags \"".$inline_tags."\"";
		$tidy_options .= " --output-file ".escapeshellarg($output_file);
    	$tidy_options .= " ".escapeshellarg($input_file);
		//echo $tidy_options."<br />".strlen($tidy_options)."<br />";
		
		$tstat = shell_exec($tidy_options);
		//echo $tstat."<br />";
		
		if (file_exists($output_file) == false) die("file cannot be automatically turned to a well-formed XHTML");
		unlink($input_file);
		copy($output_file, $input_file);
		unlink($output_file);
	}
	
	/*
		Save the time logging
		@param string $rec_note the note
		@param number $rec_time the recorded time
	 */
	function timeLog ($rec_note, $rec_time) {
		$new_data = $rec_note.": ".$rec_time."sec \n\r";
		$fh = modifyFile($GLOBALS['time_log'], 'a+') or die("can't open file");
		fwrite($fh, $new_data);
		fclose($fh);
	}
	
	/*
		Get the current time
	*/
	function now($start)
    {
        $start  = math($start);
        $now    = math(microtime());
        return round($now - $start, 3);
    }

	/*
		Do it in seconds
	*/
    function math($time){
        $temp = explode(' ', $time);
        return $temp[0] + $temp[1];
    }
	
	/*
		Getting the content from a url through a proxy if there is one 
		@param string $url the url
		@return string the content acquired from the url
	 */
	function url_get_contents($url) {
		if (strlen($GLOBALS["proxyaddr"]) > 1) {
			$auth = base64_encode($GLOBALS["username"].":".$GLOBALS["password"]);
			$opts = array('http' => array(
					'proxy' => $GLOBALS["proxyaddr"], 
					'request_fulluri' => true,
					'header' => "Proxy-Authorization: Basic ".$auth));
			$context = stream_context_create($opts);  
			return file_get_contents($url, false, $context);
		} else {
			return file_get_contents($url);
		}
	}
	
	/*
	 	Given a file path that we want to modify, make sure that the
		permission to that file is changed to rwx permission
		@param string $path the path to the folder
		@param string $mode the opening mode of the file (w or a)
		@return resource the file handle
	*/
	function modifyFile($path, $mode) {
		$mod_set = false;
		if (file_exists($path) == true) {
			chmod($path,0777);
			$mod_set = true;
		}
		$fp = @fopen($path, $mode);
		if ((!$fp) && (!$mod_set)) {
			chmod($path,0777);
		}
		return $fp;
	}
	
	/*
		Create a directory and making sure that it got rwx permission
		@param string $path the path to the new folder name
		@param int    $mode the folder permission
	 */
	function makeFolder($path, $mode) {
		$old = umask(0);
		mkdir($path,$mode);
		umask($old);
	}
	
	/*
		Get the log time
		@return string the time
	*/
	function getLogTime () {
		$gdate = now($stime);
		return str_replace(" ",",",$gdate);
	}
	
	/*
		Remove any unwanted character for the specified filename
		@param string $old_string the given filename
		@return string $old_string the returned filename
	*/
	function cleanFilename ($old_string) {
		$err_char = array ("@","_"," ","\\",".","\"","'","`","%","&","#","<",">");
		for ($i = 0; $i < count($err_char); $i++) { 
			$old_string = str_replace($err_char[$i],"-", $old_string);
		}
		$old_string = str_replace("mediaplayer","mp",$old_string);
		return $old_string;
	}
	
	/*
		Recursively removing directory and all of its content
		@param string $folder_name the path to the book directory
	*/
	function removeDirectory ($folder_name) {
		if ($handle = opendir($folder_name)) {
    	while (false !== ($file = readdir($handle))) {
     		$dir = $folder_name."/".$file;
      	if((strcmp($file,".") != 0) && (strcmp($file,"..") != 0)) {
					if (is_dir($dir)) {
						removeDirectory($dir);
					} else {
						unlink($dir);
					}
				}
    	}
			closedir($handle);
			rmdir($folder_name);
		}
	}
	
	/*
		Check that the specified filename is unique in the current book directory
		@param string $folder_name the path to the book directory
		@param array $allowedExtension the list of allowed extenstion
		@param string $filename the specified filename
		@param boolean $isOverwrite whether the old file should be overwrote
		@return string $curr_name the valid filename
	*/
	function getValidFilename($folder_name, $allowedExtension, $filename, $isOverwrite) {
		$fname = explode(".", $filename);
		//make it lowercase so it can handle windows case-insensitive system
		$curr_name = strtolower($fname[0]);
		
		//remove any unwanted character
		$curr_name = cleanFilename($curr_name);
		
		//we need to check that the chosen name does not exists
		$valid_name = $curr_name;
		$found = $isOverwrite;
		$off = 0;
		$j = 0;
		while ($found == false) {
			for ($j = 0 ; (($j < count($allowedExtension)) && ($found == false)); $j++) {
				$tst_name = $folder_name."/repository/".$valid_name.".".$allowedExtension[$j];
				if (file_exists($tst_name)) {
					$found = true;
				}
			}
			if ($found == true) {
				$valid_name = $curr_name."-".(time()+$off);
				$off = $off + 1;
				$found = false;
			} else {
				$found = true;
			}
		}
		
		$valid_name = $valid_name.".".strtolower($fname[1]);
		return $valid_name;
	}
	
	/*
		Change the permission of the file inside the book
		directory to be rwx and list all the files in it
		@param string $folder_name the path to the book directory
		@param string $toFile the string to be written to file
	*/
	function listFiles ($folder_name, $toFile) {
		if ($handle = opendir($folder_name)) {
    	while (false !== ($file = readdir($handle))) {
     		$dir = $folder_name."/".$file;
      	if((strcmp($file,".") != 0) && (strcmp($file,"..") != 0)) {
					chmod($dir, 0777);
					if (is_dir($dir)) {
						listFiles($dir);
					} else {
						$sfile = array("RealisticBook.js","RealisticBook.swf","send.php","index.html","SteelOverAll.swf","orig_book.htm");
						$file_ext = end(explode(".", strtolower($file)));
						$sext = array("flv","mp3","pdf");
						if ((!in_array($file, $sfile)) && (!in_array($file_ext, $sext)))
							$toFile = $toFile."<li>".$file."</li>\n";
					}
				}
    	}
			closedir($handle);
		}
		return $toFile;
	}
?>